const express = require('express');
const { Course, Like, User } = require('../models');
const { NotFound, BadRequest } = require('http-errors');
const { failure, success } = require('../utils/responses');
const router = express.Router();
/* 
点赞\取消点赞
GET /likes */
router.post('/', async function (req, res) {
  try {
    const userId = req.userId;
    const { courseId } = req.body;
    const course = await Course.findByPk(courseId);
    if (!course) {
      throw new NotFound('课程不存在');
    }
    console.log(userId, 'userId');
    const like = await Like.findOne({
      where: {
        courseId,
        userId,
      },
    });
    console.log(like);
    if (!like) {
      await Like.create({ courseId, userId });
      await course.increment('likesCount');
      success(res, '点赞成功');
    } else {
      await Like.destroy({
        where: { courseId, userId }, // 必须加条件，只删当前记录
      });
      await course.decrement('likesCount');
      success(res, '取消点赞成功');
    }
  } catch (error) {
    failure(res, error);
  }
});

/* 
查询用户点赞课程
GET /likes */
router.get('/', async function (req, res) {
  try {
    const query = req.query;
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    const offset = (currentPage - 1) * pageSize;
    const user = await User.findByPk(req.userId);
    const courses = await user.getLikeCourses({
      joinTableAttributes: [],
      attributes: { exclude: ['CategoryId', 'UserId', 'content'] },
      order: [['id', 'desc']],
      limit: pageSize,
      offset,
    });
    const count = await user.countLikeCourses();
    success(res, '查询成功', {
      courses,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
});
module.exports = router;
